package cc.rengu.igas.bomp.core.service.trans;

import cc.rengu.igas.bomp.common.constant.DubboMethodConstant;
import cc.rengu.igas.bomp.common.dao.AuthUserMapper;
import cc.rengu.igas.bomp.common.dao.ManagerInfoMapper;
import cc.rengu.igas.bomp.common.dao.MchntApplyInfoMapper;
import cc.rengu.igas.bomp.common.dao.RegionInfoMapper;
import cc.rengu.igas.bomp.common.dao.impl.AuthUserMapperImpl;
import cc.rengu.igas.bomp.common.dao.impl.ManagerInfoMapperImpl;
import cc.rengu.igas.bomp.common.dao.impl.MchntApplyInfoMapperImpl;
import cc.rengu.igas.bomp.common.dao.impl.RegionInfoMapperImpl;
import cc.rengu.igas.bomp.common.entity.AuthUser;
import cc.rengu.igas.bomp.common.entity.ManagerInfo;
import cc.rengu.igas.bomp.common.entity.MchntApplyInfo;
import cc.rengu.igas.bomp.common.entity.RegionInfo;
import cc.rengu.igas.bomp.common.enums.RespCodeEnum;
import cc.rengu.igas.bomp.core.service.base.ManageService;
import cc.rengu.igas.bomp.facade.request.MchntEntryDispatchRequest;
import cc.rengu.igas.bomp.facade.response.MchntEntryDispatchResponse;
import cc.rengu.igas.channel.wechat.facade.base.Header;
import cc.rengu.igas.channel.wechat.facade.request.DispatchMsgPushRequest;
import cc.rengu.igas.channel.wechat.facade.request.MchntApplyAcceptMsgPushRequest;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.entity.ChannelCallCfg;
import cc.rengu.oltp.service.common.enums.ChannelEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.service.realize.DubboService;
import cc.rengu.oltp.service.realize.impl.DubboServiceImpl;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.DateUtil;
import cc.rengu.oltp.utility.util.StringUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhangxuran
 * @version 1.0
 * @date 2020.03.27
 */
public class MchntEntryDispatchService extends ManageService {
    @Override
    protected Object bizBeforeCust() throws Exception {
        MchntEntryDispatchRequest mchntEntryDispatchRequest = new MchntEntryDispatchRequest();
        ConvertUtil.convertOutput(mchntEntryDispatchRequest);
        return mchntEntryDispatchRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {

        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();

        MchntEntryDispatchRequest mchntEntryDispatchRequest = (MchntEntryDispatchRequest) request;
        MchntEntryDispatchResponse mchntEntryDispatchResponse = new MchntEntryDispatchResponse();
        /* 获取法人行标识 */
        String instId = mchntEntryDispatchRequest.getHeader().getInstId();
        /* 获取用户标识*/
        String userId = mchntEntryDispatchRequest.getUserId();
        /*入驻申请单号*/
        String applyId = mchntEntryDispatchRequest.getApplyId();
        /*拓展经理工号*/
        String managerId = mchntEntryDispatchRequest.getManagerId();
        /*签约机构ID*/
        String signInstId = mchntEntryDispatchRequest.getSignInstId();

        if (StringUtil.isEmptyOrNull(instId) || StringUtil.isEmptyOrNull(userId) || StringUtil.isEmptyOrNull(applyId) || StringUtil.isEmptyOrNull(managerId) || StringUtil.isEmptyOrNull(signInstId)) {
            rglog.error("必填性校验失败!");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }


        BizResponse<MchntEntryDispatchResponse> bizResponse = new BizResponse<>();
        bizResponse.setRspSysId(AppParamConstant.SYS_ID);
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());

        /* 根据用户标识获取派单人信息 */
        AuthUserMapper authUserMapper = new AuthUserMapperImpl();
        AuthUser authUser = authUserMapper.selectAuthUserById(userId);
        if (null == authUser) {
            rglog.error("派单人信息查询失败");
            bizResponse.setRespCode(RespCodeEnum.QUERY_AUTH_USER_IS_NULL.getRespCode());
            bizResponse.setRespDesc(RespCodeEnum.QUERY_AUTH_USER_IS_NULL.getRespDesc());
            bizResponse.setResult(mchntEntryDispatchResponse);
            return bizResponse;
        }

        /* 获取被派单拓展经理相关信息 */
        ManagerInfoMapper managerInfoMapper = new ManagerInfoMapperImpl();
        ManagerInfo managerInfo = managerInfoMapper.selectManagerInfoByPrimaryKey(instId, signInstId, managerId);
        if (null == managerInfo) {
            rglog.error("派单拓展经理信息查询失败");
            bizResponse.setRespCode(RespCodeEnum.QUERY_MANAGER_INFO_ERROR.getRespCode());
            bizResponse.setRespDesc(RespCodeEnum.QUERY_MANAGER_INFO_ERROR.getRespDesc());
            bizResponse.setResult(mchntEntryDispatchResponse);
            return bizResponse;
        }
        /* 获取申请商户信息 */
        MchntApplyInfoMapper mchntApplyInfoMapper = new MchntApplyInfoMapperImpl();
        MchntApplyInfo mchntApplyInfo = mchntApplyInfoMapper.selectMchntApplyInfoByPrimaryKey(instId, applyId);
        if (null == mchntApplyInfo) {
            rglog.error("商户申请信息查询失败");
            bizResponse.setRespCode(RespCodeEnum.QUERY_MCHNT_APPLY_INFO_ERROR.getRespCode());
            bizResponse.setRespDesc(RespCodeEnum.QUERY_MCHNT_APPLY_INFO_ERROR.getRespDesc());
            bizResponse.setResult(mchntEntryDispatchResponse);
            return bizResponse;
        }
        /*dubbo请求初始化*/
        DispatchMsgPushRequest dispatchMsgPushRequest = new DispatchMsgPushRequest();
        //获取通道标识,设置通道标识（需要修改，通道标识和通道序号，这个是从交易码映射表中获取）
        List<ChannelCallCfg> channelCallCfgList = txnInfo.getChannelCallCfgList();
        List<ChannelCallCfg> msgDstchannelCallCfgList = channelCallCfgList.stream().filter(item -> item.getCallChannelId().equals("WXZF")).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(msgDstchannelCallCfgList)) {
            rglog.error("微信通道交易未配置！");
            throw new BizException(RespCodeEnum.CONFIG_PARAM_NOT_EXIST.getRespCode(), RespCodeEnum.CONFIG_PARAM_NOT_EXIST.getRespDesc());
        }
        ChannelCallCfg channelCallCfg = msgDstchannelCallCfgList.get(0);
        dispatchMsgPushRequest.setChannelId(channelCallCfg.getCallChannelId());
        Header header = new Header();
        header.setInstId(instId);
        header.setBizType(channelCallCfg.getBizType());
        header.setSrcSysId(AppParamConstant.SYS_ID);
        header.setChanlId(channelCallCfg.getMsgSrcId());
        header.setTxnNum(channelCallCfg.getCallChannelTxn());
        header.setTraceNo(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM));
        header.setTransDate(DateUtil.getCurrentDate());
        header.setTransTime(DateUtil.getCurrentTime());
        header.setVersion("1.0.0");
        dispatchMsgPushRequest.setHeader(header);
        /*派单人信息赋值*/
        dispatchMsgPushRequest.setDispatchName(authUser.getEmpName());
        /*拓展经理微信信息赋值*/
        dispatchMsgPushRequest.setOpenId(managerInfo.getOpenId());
        /*商户名称赋值*/
        dispatchMsgPushRequest.setMchntName(mchntApplyInfo.getMchntName());
        /*商户经营地址赋值*/
        dispatchMsgPushRequest.setAddress(mchntApplyInfo.getAddress());
        /*商户联系人赋值*/
        dispatchMsgPushRequest.setMchntContact(mchntApplyInfo.getContactName());
        /*联系人电话赋值*/
        dispatchMsgPushRequest.setContactPhoneNo(mchntApplyInfo.getContactPhone());
        /* 根据地区编码查询地区名称 */
        RegionInfoMapper regionInfoMapper = new RegionInfoMapperImpl();
        RegionInfo regionInfo = regionInfoMapper.selectRegionInfoByPrimaryKey(mchntApplyInfo.getArea());
        if (null != regionInfo) {
            dispatchMsgPushRequest.setLocation(regionInfo.getRegionName());
        } else {
            rglog.error("地区信息查询失败！");
        }

        /* 调用dobbu服务*/
        DubboService dubboService = new DubboServiceImpl();
        int iReturnCode = dubboService.asynCallDubboService(DubboMethodConstant.DUBBO_WECHAT_MSGPUSH_SERVICE, "dispatchMsgPush", dispatchMsgPushRequest, null);
        if (iReturnCode != 0) {
            rglog.error("微信推送商户入驻派单通知给拓展经理(调用duboo)处理失败，instId:<{}>,managerId:<{}>", instId, managerId);
        } else {
            rglog.info("微信推送商户入驻派单通知给拓展经理(调用duboo)处理成功，instId:<{}>,managerId:<{}>", instId, managerId);
            /*异步消息推送请求报文信息拼装*/
            MchntApplyAcceptMsgPushRequest mchntApplyAcceptMsgPushRequest = new MchntApplyAcceptMsgPushRequest();
            header = new Header();

            header.setInstId(instId);
            header.setSrcSysId(AppParamConstant.SYS_ID);
            header.setChanlId(ChannelEnum.BOMP.getChannelType());
            header.setBizType("00");
            header.setVersion("1.0.0");
            header.setTransDate(DateUtil.getCurrentDate());
            header.setTransTime(DateUtil.getCurrentTime());
            header.setTxnNum("applyaccept");
            header.setTraceNo(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM));
            mchntApplyAcceptMsgPushRequest.setHeader(header);
            /* 渠道标识赋值*/
            mchntApplyAcceptMsgPushRequest.setChannelId(ChannelEnum.WXZF.getChannelType());
            /*商户openId赋值*/
            mchntApplyAcceptMsgPushRequest.setOpenId(mchntApplyInfo.getOpenId());
            /*拓展经理姓名赋值*/
            mchntApplyAcceptMsgPushRequest.setAcceptName(managerInfo.getManagerName());
            /*拓展经理手机号赋值*/
            mchntApplyAcceptMsgPushRequest.setPhoneNo(managerInfo.getManagerPhone());

            iReturnCode = dubboService.asynCallDubboService(DubboMethodConstant.DUBBO_WECHAT_MSGPUSH_SERVICE, "mchntApplyAcceptMsgPush", mchntApplyAcceptMsgPushRequest, null);
            if (iReturnCode != 0) {
                rglog.error("微信推送商户入驻派单通知给商户(调用duboo)处理失败，instId:<{}>,mchntName:<{}>,contactPhone:<{}>", instId, mchntApplyInfo.getMchntName(), mchntApplyInfo.getContactPhone());
            } else {
                rglog.error("微信推送商户入驻派单通知给商户(调用duboo)处理成功，instId:<{}>,mchntName:<{}>,contactPhone:<{}>", instId, mchntApplyInfo.getMchntName(), mchntApplyInfo.getContactPhone());
            }
        }
        bizResponse.setResult(mchntEntryDispatchResponse);
        return bizResponse;
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        MchntEntryDispatchResponse mchntEntryDispatchResponse = (MchntEntryDispatchResponse) bizResponse.getResult();
        ConvertUtil.convertInput(mchntEntryDispatchResponse);
    }
}
